package com.qf.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/5/8
 * @desc
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)// 开启注解开发,允许使用@Secured和@PreXxx和@Postxxx注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

        @Autowired
        private AuthenticationEntryPointImpl unauthorizedHandler;

        @Autowired
        private MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    // 新增代码，用于获取AuthenticationManager对象，在登录的业务层进行调用
    @Bean// 将其注入到容器
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 认证(登录)使用的配置方法
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用框架中提供的BCryptPasswordEncoder对密码进行加密后校验
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 授权(权限)使用的配置方法
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 注解开发的配置
         */
        http.authorizeRequests()
                // 允许任何人访问，不管是否登录
                .antMatchers("/**/*.js", "/**/*.css","/user/login2","/user/logout2","/user/register").permitAll()
                // 其他资源需要认证后才能访问，比如/hello
                .antMatchers("/**").authenticated();

        http.csrf().disable(); // 禁用CSRF防护,否则无法使用Post请求
        // 【重点】基于token，所以不需要session，即所以认证信息都存放在token中，不需要session
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 指定权限异常处理类
        // http.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler));
        http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        // 指定jwt解析拦截器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

